package consumer

import (
	"encoding/json"
	"log"

	"gitee.com/shiwjlinux/shoplink/config"
	"gitee.com/shiwjlinux/shoplink/models"
	"gitee.com/shiwjlinux/shoplink/utils"
	"github.com/streadway/amqp"
)

func ConsumeOrder() {
	conn, ch, err := utils.ConnectToRabbitMQ()
	if err != nil {
		return
	}

	defer conn.Close()
	defer ch.Close()

	q, err := utils.DeclareQueue(ch, config.OrderQueue)
	if err != nil {
		return
	}

	msgs, err := ch.Consume(q.Name, "", false, false, false, false, nil)
	if err != nil {
		return
	}
	forever := make(chan bool)
	go func() {
		for data := range msgs {
			var order models.Order
			err := json.Unmarshal(data.Body, &order)
			if err != nil {
				data.Nack(false, false)
				continue
			}

			if processOrder(order) {
				log.Printf("Order %s processed successfully", order.OrderID)
				data.Ack(false)
			} else {
				log.Printf("Failed to process order %s", order.OrderID)
				// data.Nack(false, true)
				SendToRetryQueue(ch, data.Body)
				data.Ack(false)
			}

		}
	}()

	<-forever
}

func processOrder(order models.Order) bool {
	return true
}

func SendToRetryQueue(ch *amqp.Channel, body []byte) {
	_, err := utils.DeclareQueue(ch, config.RetryQueue)
	if err != nil {
		return
	}

	if err := utils.PublishMessage(ch, config.RetryQueue, body); err != nil {
		return
	}
}
